package com.taobao.top.demo.getData;

import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.taobao.top.demo.common.ConvertProperties;
import com.taobao.top.demo.common.DemoConstant;
import com.taobao.top.demo.common.Util;
import com.taobao.top.demo.dataobject.Item;
import com.taobao.top.demo.dataobject.PropImg;
import com.taobao.top.demo.exception.DemoException;
/**
 * 调用 taobao.item.get
 * 获得item信息
 * @author Jessica
 *
 */
public class GetItem {
	/**
	 * 组装请求参数
	 * @param sessionKey 
	 * @param nick 用户nick
	 * @param iid 商品iid
	 * @return
	 */
	private static String createRequestParam(String sessionKey,String nick,String iid){
		TreeMap<String,String> apiparamsMap = new TreeMap<String,String>();
		// 组装协议参数。
		apiparamsMap.put("method", "taobao.item.get");
		apiparamsMap.put("app_key", DemoConstant.APP_KEY);
		apiparamsMap.put("timestamp", new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		apiparamsMap.put("session", sessionKey);
		apiparamsMap.put("format", "xml");
		apiparamsMap.put("v", "2.0");
		// 组装应用参数
		apiparamsMap.put("fields", "iid,nick,title,prop_img,cid,property_alias");
		apiparamsMap.put("nick", nick);
		apiparamsMap.put("iid", iid);
		//生成签名
		String sign = Util.sign(apiparamsMap, DemoConstant.APP_SERCET);
		//组装协议参数sign
		apiparamsMap.put("sign", sign);
		
		StringBuilder param = new StringBuilder();
		for (Iterator<Map.Entry<String, String>> it = apiparamsMap.entrySet()
				.iterator(); it.hasNext();) {
			Map.Entry<String, String> e = it.next();
			param.append("&").append(e.getKey()).append("=").append(
					e.getValue());
		}
		return param.toString().substring(1);
	}
	
	/**
	 * 调用api，获得结果，对返回结果组装成对象
	 * @param sessionKey
	 * @param nick 用户nick
	 * @param iid 商品iid
	 * @return item对象
	 * @throws DemoException 自定义异常
	 */
	public static Item getItem(String sessionKey,String nick,String iid) throws DemoException {
		//获得组装请求参数
		String paramStr = createRequestParam(sessionKey,nick,iid);
		//调用API，获得返回结果
		String resultStr = Util.getResult(DemoConstant.SANDBOX_URL,paramStr);
		
		//对返回的xml结果字符串，进行解析，组装成java对象
		StringReader read = new StringReader(resultStr);
		InputSource source = new InputSource(read);
		SAXBuilder builder = new SAXBuilder();
		Item item = null;
		List<PropImg> propImgs = new ArrayList<PropImg>();
		try {
			Document document = builder.build(source);
			Element root = document.getRootElement();
			Element ele = root.getChild("item");
			if(ele == null){
				throw new DemoException("获取信息失败");
			}
			item = new Item();
			item.setIid(ele.getChildText("iid"));
			item.setNick(ele.getChildText("nick"));
			item.setTitle(ele.getChildText("title"));
			item.setCid(ele.getChildText("cid"));
			String propertyAlias = ele.getChildText("property_alias");
			item.setPropertyAlias(propertyAlias);
			String[] pAlias = propertyAlias.split(";");
			Element propImgsEle = ele.getChild("prop_imgs");
			List<Element> propImgEle = null;
			if(propImgsEle != null){
				propImgEle =  propImgsEle.getChildren();
				propImgs = new ArrayList<PropImg>();
				for(int i = 0; i < propImgEle.size(); i++){
					PropImg propImg = new PropImg();
					Element prop = propImgEle.get(i);
					propImg.setProperties(prop.getChildText("properties"));
					for(int j = 0; j < pAlias.length; j++){
						if(pAlias[j].startsWith(propImg.getProperties())){
							String nameAlias = pAlias[j].substring(propImg.getProperties().length()+ 1);
							propImg.setNameAlias(nameAlias);
							break;
						}
					}
					propImg.setUrl(prop.getChildText("url"));
					propImg.setPropimgId(prop.getChildText("id"));
					propImgs.add(propImg);
					
				}
				ConvertProperties.setColorName(propImgs, item.getCid());
				item.setPropImgs(propImgs);
			}
		} catch (JDOMException e) {
			throw new DemoException("返回结果出错!");
		} catch (IOException e) {
			throw new DemoException("返回结果出错!");
		} 
		return item;
	}
	
}
